package com.example.practice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.practice.example.ParentChild;
import com.example.practice.example.ParentChildTree;
import com.example.practice.mapper.ParentChildMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/10/15 17:39
 */
@RestController
public class ParentChildController {

    @Autowired
    private ParentChildMapper parentChildMapper;

    public ArrayList<ParentChildTree> a() {
        ArrayList<ParentChildTree> arrayList = Lists.newArrayList();
        LambdaQueryWrapper<ParentChild> parentChildLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ParentChild> parentChildren = parentChildMapper.selectList(parentChildLambdaQueryWrapper);

        List<ParentChildTree> collect1 = parentChildren.stream().map(obj -> {
            ParentChildTree tree = new ParentChildTree();
            BeanUtils.copyProperties(obj, tree);
            return tree;
        }).collect(Collectors.toList());

        Map<Integer, ParentChildTree> collect = collect1.stream().collect(Collectors.toMap(ParentChildTree::getId, p -> p));

        collect1.forEach(obj -> {
            ParentChildTree tree = collect.get(obj.getPid());
            if (Objects.isNull(tree)) {
                arrayList.add(obj);
            } else {
                tree.getChild().add(obj);
            }
        });
        return arrayList;
    }


    public ArrayList<ParentChild> b() {
        ArrayList<ParentChild> arrayList = Lists.newArrayList();
        LambdaQueryWrapper<ParentChild> parentChildLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ParentChild> parentChildren = parentChildMapper.selectList(parentChildLambdaQueryWrapper);
        Map<Integer, ParentChild> collect1 = parentChildren.stream().collect(Collectors.toMap(ParentChild::getId, p -> p));
        parentChildren.forEach(obj -> {
            ParentChild tree = collect1.get(obj.getPid());
            if (Objects.isNull(tree)) {
                arrayList.add(obj);
            } else {
                tree.getChild().add(obj);
            }
        });
        return arrayList;
    }
}
